// pages/music/index.js
const ac = wx.getBackgroundAudioManager()
let lastIndex
Page({
	onReachBottom(){
		console.log('onReachBottom~')
		// console.log(JSON.stringify(this.data.songs[9]))
		// let change={}
		// change[`songs[10]`]={ //新增数组元素
		// 	"id":1990105530,
		// 	"name":"美丽的草原我的家22",
		// 	"duration":"13:53",
		// 	"album":"蒋大为独唱歌曲选22"
		// }
		this.request(this.data.search)
	},
	pause(a) {
		console.log(this.data.paused ? '播放play' : '暂停pause')
		let paused = !this.data.paused
		if (paused) ac.pause()
		else ac.play()
		this.setData({
			paused
		})
	},
	play(a) {
		let index = a.currentTarget.dataset.index
		// let songs = this.data.songs
		// if(lastIndex!=null)songs[lastIndex].selected=false
		// songs[index].selected = true
		// lastIndex=index
		// this.setData({songs})
		let change = {
			paused: false
		}
		if (lastIndex != null) {
			if (index == lastIndex) return
			change[`songs[${lastIndex}].selected`] = false
		}
		change[`songs[${index}].selected`] = true
		lastIndex = index
		this.setData(change)
		let id = this.data.songs[index].id
		let mp3 = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
		console.log(mp3)
		ac.src = mp3
		ac.title=this.data.songs[index].name
		// ac.startTime=180
		ac.play()
	},
	formatDuration(ms) {
		ms = parseInt(ms / 1000)
		let minute = parseInt(ms / 60)
		ms %= 60
		return minute + ":" + (ms < 10 ? '0' : '') + ms
  },
  onUnload(){
		let songMessage=this.data
		songMessage.lastIndex=lastIndex
		delete songMessage.__webviewId__
		delete songMessage.inputKey
		wx.setStorageSync('songMessage', songMessage)//缓存数据到手机
  },
	onLoad(options) { //生命周期函数--监听页面加载
		let songMessage=wx.getStorageSync('songMessage')
		console.log(songMessage, typeof songMessage)
		if(songMessage){
			lastIndex=songMessage.lastIndex//恢复原来播放歌曲的索引号
			delete songMessage.lastIndex
			this.setData(songMessage)
		}
		ac.onEnded(() => {
			let index = lastIndex + 1
			if (index == this.data.songs.length) index = 0
			this.play({
				currentTarget: {
					dataset: {
						index
					}
				}
			})
		})
	// this.search({detail:{value:'蒋大为'}})
	},
	search(a) {
		let search = a.detail.value.trim()
		if (!search) return
		this.setData({search, inputKey:'', songs:[]})
		this.request(search)
	},
	request(key) {
		let offset=this.data.songs.length
		if(offset>=this.data.songCount)return
		wx.request({
			url: `https://music.163.com/api/search/get/?s=${key}&limit=50&type=1&offset=${offset}`,
			complete: r => {
				console.log(r)
				if (r.errMsg == "request:ok" && r.data.result.songs) {
					// let songs = []
					let change={songCount: r.data.result.songCount}
					r.data.result.songs.forEach(item => {
						change[`songs[${offset++}]`]={
							id: item.id,
							name: item.name,
							duration: this.formatDuration(item.duration),
							album: item.album.name,
						}
					})
					this.setData(change)
				}
			}
		})
	}
})